package easy.汉明距离;

import org.junit.Test;

/*
两个整数之间的汉明距离是相应位不同的位置数。
给定两个整数x和y，计算汉明距离。
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑
The above arrows point to positions where the corresponding bits are different.
 */
public class Solution {
    //利用移位
    public int hammingDistance(int x, int y) {
        int res=x^y;
        int result=0;
        int cmath= 2;
        for (int i = 0; i < 32; i++) {
            int m=res%cmath;
            if (m==1){
                result +=1;
            }
            res=res>>1;
        }
        return result;
    }
    //利用字符串
    public int hammingDistance2(int x, int y) {
        int res=x^y;
        int result=0;
        String resstr=Integer.toBinaryString(res);
        for (int i = 0; i < resstr.length(); i++) {
            if ('1'== resstr.charAt(i)){
                result++;
            }
        }
        return result;
    }
    @Test
    public void test1(){
        Solution solution=new Solution();
        System.out.println(solution.hammingDistance2(1,3));

    }
}
